var curAreaIndex = undefined;
var curOutline = undefined;
var myCanvas;
$(document).ready(function(){
    
    //drawing canvas
    var CanvasDesigner = function(){
        this.scale = 10;
        this.posX = 1;
        this.posY = 1;
        this.zoomIn = function(){
            this.setScale(this.scale*2);
        };
        this.zoomOut = function(){
            this.setScale(this.scale/2);
        };
        this.setScale = function(scale){
            this.scale = scale;
            this.renderStage();
        };
        this.setPos = function(posX, posY){
            this.posX = posX;
            this.posY = posY;
            this.renderStage();
        };
        this.calcScalePosX = function(xVal){
            var retVal = 0;
            retVal = (this.posX*1 + xVal*1)*this.scale;
            return retVal;
        };
        this.calcScalePosY = function(yVal){
            var retVal = 0;
            retVal = (this.posY*1 + yVal*1)*this.scale;
            return retVal;
        };
        this.renderStage = function(){
            /* create element*/
            R.clear();
            $('#list-form li').each(function(index){
                var myJSON = eval($(this).find('.hidden_area_outline').val());
                var $retVal = '';
                
                for(var i = 0; i< myJSON.length; i++){
                    R.circle(myCanvas.calcScalePosX(myJSON[i].posX), myCanvas.calcScalePosY(myJSON[i].posY),10)
                    .attr("fill", "#f00")
                    .attr("stroke", "#f00")
                    .attr("cursor", "pointer");
                    if(i == 0){
                        $retVal = 'M' + myCanvas.calcScalePosX(myJSON[0].posX) + ' ' + myCanvas.calcScalePosY(myJSON[0].posY);
                    }else{
                        $retVal += 'L'+myCanvas.calcScalePosX(myJSON[i].posX) + ' ' + myCanvas.calcScalePosY(myJSON[i].posY);
                    }
                }
                if(myJSON.length > 0){
                    $retVal += 'L'+myCanvas.calcScalePosX(myJSON[0].posX) + ' ' + myCanvas.calcScalePosY(myJSON[0].posY);
                }
                R.path($retVal).attr("fill", "#00ff01");
            });
        };
    }
    myCanvas = new CanvasDesigner();
    var R = Raphael("svgcanvas", "100%", "100%");
    myCanvas.renderStage();
    //read data from html
    $('#list-form li').each(function(index){
        var area_name = $(this).find('.hidden_area_name').val();
        console.log(index, $(this));
        $('#select-area-name').append('<option>'+area_name+'</option>');
    });
    curAreaIndex = $('#select-area-name')[0].selectedIndex;
    loadResource();
    //add event
    $('#select-area-name').change(function(){
        curAreaIndex = $('#select-area-name')[0].selectedIndex;
        loadResource();
    });
    $('#create-area').click(createArea);
    $('#destroy-area').click(deleteArea);
    $('#area_name').change(function(){
        var $item = $($('#select-area-name option').get(curAreaIndex));
        $item.html($(this).val());
        $item = $($('#list-form li').get(curAreaIndex));
        $item.find('.hidden_area_name').val($(this).val());
    });
    $('#area_type_id').change(function(){
        $item = $($('#list-form li').get(curAreaIndex));
        $item.find('.hidden_area_type_id').val($(this).val());
    });
    $('#add-point').click(function(){
        createPoint({
            'posX':0, 
            'posY':0
        });
        updateOutline();
    });
    $('.posX, .posY').unbind('change',updateOutline);
    $('.posX, .posY').bind('change',updateOutline);
    $('.destroy').unbind('click',destroyPoint);
    $('.destroy').bind('click',destroyPoint);
});
var destroyPoint = function(){
    $(this).parent().parent().remove();
    updateOutline();
}
function createArea(){
    var htmlAreaInput = $('#areaInputTemplate').html();
    $('#list-form').append(htmlAreaInput);
    $('#select-area-name').append('<option></option>');
    $('#select-area-name option:last-child').attr('selected', true);
    curAreaIndex = $('#select-area-name')[0].selectedIndex;
    curOutline = [];
    $('#tablePoint tbody').html('');
    loadResource();
}
var deleteArea = function(event){
    $($('#list-form li').get(curAreaIndex)).remove();
    $($('#select-area-name option').get(curAreaIndex)).remove();
    myCanvas.renderStage();
}
var loadResource = function(event){
    var $item = $($('#list-form li').get(curAreaIndex));
    $('#area_name').val($item.find('.hidden_area_name').val());
    $('#area_type_id').val($item.find('.hidden_area_type_id').val());
    $('#area_size').val($item.find('.hidden_area_size').val());
    //$('#tablePoint tbody').html($item.find('.hidden_area_outline').val());
    $('#tablePoint tbody').html('');
    createTableList($item.find('.hidden_area_outline').val());
}
var createTableList = function(val){
    var myJSON = eval(val);
    for(var i = 0; i< myJSON.length; i++){
        createPoint(myJSON[i]);
    }
    updateOutline();
}
var createPoint = function(point){
    console.log('point', point);
    var html = $('#pointTemplate').html()
    .replace(/<%=posX %>/g,point.posX)
    .replace(/<%=posY %>/g,point.posY);
    $('#tablePoint tbody').append(html);
    $('.posX, .posY').unbind('change',updateOutline);
    $('.posX, .posY').bind('change',updateOutline);
    $('.destroy').unbind('click',destroyPoint);
    $('.destroy').bind('click',destroyPoint);
}
var updateOutline = function(){
    var $item = $($('#list-form li').get(curAreaIndex));
    var myJSON = [];
    $('#tablePoint tbody tr').each(function(index){
        myJSON.push({
            posX:$(this).find('.posX').val(), 
            posY:$(this).find('.posY').val()
        });
    });
    $item.find('.hidden_area_outline').val(JSON.stringify(myJSON));
    var leftSum = 0;
    var rightSum = 0;
    for(var i =1; i< myJSON.length; i++){
        leftSum += myJSON[i].posX * myJSON[i-1].posY;
        leftSum += myJSON[i].posY * myJSON[i-1].posX;
    }
    leftSum += myJSON[0].posX * myJSON[myJSON.length-1].posY;
    leftSum += myJSON[0].posY * myJSON[myJSON.length-1].posX;
    var size = Math.abs(leftSum - rightSum)/2;
    $item.find('.hidden_area_size').val(size.toFixed(3));
    $('#area_size').val(size.toFixed(3));
    myCanvas.renderStage();
}